import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/login'
    }, {
        path: '/login',
        component: () =>
            import ('../components/Login.vue')
    }, {
        path: '/home',
        component: () =>
            import ('../components/Home.vue'),
        redirect: '/welcome',
        children: [{
                path: '/welcome',
                component: () =>
                    import ('../components/WelCome.vue')
            }, {
                path: '/seat',
                component: () =>
                    import ('../components/seat/seat.vue')
            }, {
                path: '/card',
                component: () =>
                    import ('../components/card/card.vue')
            }, {
                path: '/fixedEntry',
                component: () =>
                    import ('../components/fixed/fixedEntry.vue')
            }, {
                path: '/fixedOut',
                component: () =>
                    import ('../components/fixed/fixedOut.vue')
            }, {
                path: '/temp',
                component: () =>
                    import ('../components/temp/temp.vue')
            },
            {
                path: '/user',
                component: () =>
                    import ('../components/sys/user.vue')
            }, {
                path: '/role',
                component: () =>
                    import ('../components/sys/role.vue')
            }
        ]
    }

]


function getCookie(c_name) {
    if (document.cookie.length > 0) {
        let c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            let c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

const router = new VueRouter({
    routes
})


// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // to and from are both route objects. must call `next`.
    // to 将要访问的路径
    // from 代表从那个路径跳转而来
    // next 是一个函数，表示放行
    //    next() 放行    next('/login) 强制跳转到 /login

    if (to.path == '/exit') {
        delCookie('token')
    }

    // 如果用户访问的登录页，直接放行
    if (to.path == '/login') return next();
    // 从cookies 中获取 保存的 token值
    const tokenStr = getCookie('token');
    // 没有 token 强制跳转到登录页
    if (!tokenStr) return next('/login');

    next()

})


export default router